<template>
    <div class="orderListRuleForm">
        <panle title='员工列表' content="员工列表"></panle>

        <el-form :inline="true" ref="form" :model="form" label-width="80px" class="demo-form-inline">
            <el-form-item label="员工" prop="staff_name">
                <el-select v-model="form.value" size="mini" filterable placeholder="请选择">
                    <el-option
                        v-for="item in options"
                        :key="item.label"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="branch_name">
                <el-select v-model="form.value1" size="mini" filterable placeholder="请选择">
                    <el-option
                        v-for="item in optionsVa"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
          
           
            <el-form-item>
                <el-button type="primary" @click="search" size="mini">搜索</el-button>
                <el-button @click="resetForm('form')" size="mini">重置</el-button>
                <el-button size="mini" @click="init()">刷新</el-button>
                
            </el-form-item>
            <div class="searchbar">
                <el-row class="pt20">
                    <el-col :span="24" style="text-align: right;">
                        <el-button type="primary" size="mini" @click="syncConfirm" :loading="loading">同步</el-button>
                    </el-col>
                </el-row>
            </div>
        </el-form>
      
        <div class="table-wrap">
            <el-table :data="tableData" :loading="loading" style="width: 100%;margin-bottom: 20px;" row-key="id" border
                      stripe default-expand-all>
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="员工"></el-table-column>
                <el-table-column prop="branch_name" label="所属部门"></el-table-column>
                <el-table-column prop="gender" label="性别"></el-table-column>
                <el-table-column prop="hide_mobile" label="手机号"></el-table-column>
                <el-table-column prop="position" label="职务"></el-table-column>
                <el-table-column prop="alias" label="别名"></el-table-column>
                <el-table-column prop="qr_code" label="个人二维码">
                    <template slot-scope="scope">
                        <el-image :src="scope.row.qr_code" fit="fill" style="width: 60px;height: 60px;"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="激活状态"></el-table-column>
                <el-table-column prop="create_time" label="同步时间"></el-table-column>
                <!--<el-table-column prop="id" label="操作" >-->
                <!--    <template slot-scope="scope">-->
                <!--        <PersButton v-if="['已激活','已禁用','未激活'].includes(scope.row.status)" type="primary" size="mini" label="编辑" icon="el-icon-edit" circle perms="sys:common:editCommon" @click="editStaff(scope.row)"></PersButton>-->
                <!--        <PersButton v-if="['已激活','已禁用','未激活'].includes(scope.row.status)" type="danger" size="mini" icon="el-icon-delete" circle perms="sys:staff:del" label="删除" @click="delStaff(scope.row)"></PersButton>-->
                <!--    </template>-->
                <!--</el-table-column>-->
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                               :current-page="form.pageNumber" :page-sizes="[10, 50, 100, 200]"
                               :page-size="form.pageSize"
                               background layout="total, sizes, prev, pager, next, jumper"
                               :total="form.total"></el-pagination>
            </div>
        </div>
        <el-dialog :visible.sync="open" width="900px" append-to-body :title="'编辑员工'">
            <el-form ref="form" :model="form"  label-width="80px">
                <el-row>

                    <el-col :span="14">
                        <el-form-item label="员工" prop="name">
                            <el-input v-model="form.name" placeholder="" size="small" />
                        </el-form-item>
                    </el-col>
                  
                    <el-col :span="14">
                        <el-form-item label="性别" prop="gender">
                            <el-radio-group v-model="form.gender">
                                <el-radio label="男"></el-radio>
                                <el-radio label="女"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item label="别名" prop="alias">
                            <el-input v-model="form.alias" placeholder="" size="small" />
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="open = false" size="small">取 消</el-button>
                <el-button type="primary" @click=" subEditForm('form') " size="small">确 定</el-button>
            </div>

        </el-dialog>
    </div>
</template>

<script>
import { getStaffData} from "@/api/scrm/lapsed/lapsed";

import Panle from '@/components/Panle';
import PersButton from '@/components/PersButton';
import VueJsonExcel from 'vue-json-excel';
import {getRemindData, getRemindLossData, sendRemind} from "@/api/scrm/remind/remind";
import {
    delUser,
    department, editUser,
    getStaffInfoData,
    syncEmployee,
    syncEmployeeDesc
} from "@/api/scrm/business/staff";
import {delCommon} from "@/api/scrm/staff/shortcutend";
import {getClientDetail, getClientIdList} from "@/api/scrm/client/clientList";

export default {
    name:'Live-Order',
    components: {
        Panle, 
        PersButton,
        VueJsonExcel
    },
    data() {
        return {
            options: [],
            value: '',
            open: false,
            tableData: [],
            number:0,
            pageSize: 10, //一页显示多少条
            pageNumber: 1,
            total: 0, //总页数
            value_1: true,
            value_2: true,
            form: {
                pageSize: 10,
                pageNumber: 1,
                total: 0,
             
            },
            reform:{
                pageSize: 10,
                pageNumber: 1,
                total: 0,
            },
            optionsVa: [],
            value1: [],
           
            resForm: {
                "status":0,
                "value1":[]
            },
            pickerOptions: {
                shortcuts: [
                    {
                        text: '今天',
                        onClick(picker) {
                            const current = new Date();
                            const month = current.getFullYear() + '-' + (current.getMonth() + 1) + '-' + current.getDate(); //年月日
                            const start = new Date();
                            const end = new Date();
                            start.setTime(new Date(month).getTime());
                            end.setTime(new Date(month + ' 23:59:59').getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '昨天',
                        onClick(picker) {
                            const current = new Date();
                            const month = current.getFullYear() + '-' + (current.getMonth() + 1) + '-' + (current.getDate() - 1); //年月日
                            const start = new Date();
                            const end = new Date();
                            start.setTime(new Date(month).getTime());
                            end.setTime(new Date(month + ' 23:59:59').getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    },
                    {
                        text: '上一周',
                        onClick(picker) {
                            const current = new Date();
                            const start_day = current.getDate() - current.getDay() - 6;
                            const end_day = current.getDate() - current.getDay();
                            const month = current.getFullYear() + '-' + (current.getMonth() + 1) + '-'; //年月
                            const start = new Date();
                            const end = new Date();
                            start.setTime(new Date(month + start_day).getTime());
                            end.setTime(new Date(month + end_day + ' 23:59:59').getTime());
                            picker.$emit('pick', [start, end]);
                        }
                    }
                ]
            },
            excelFields: {
                "客户 ": "client_name",
                "添加员工": "staff_name",
                "企业标签": "tag_name",
                "流失时间": "lapsed_time",
                "添加时间": "add_time",
                "添加员工时长（天）": "day_time",
              
            }
        }
    },
    created() {
        sessionStorage.removeItem('live-stat')

        this.getSiftSelect();
        this.init();
    },
    methods: {
        // 筛选列表备选数据初始化
        getSiftSelect() {
            getStaffData(this.form).then((res) => {
                this.options = res.data;
            })
            department(this.form).then((res) => {
                this.optionsVa = res.data;
            })
        },
        // 初始化列表数据
        init() {
            this.loading = true;
            let param = {
                "pageSize": this.pageSize,
                "pageNumber": this.pageNumber,
                "keyword": this.serachword
            }
            getStaffInfoData(this.form).then((row) => {
                this.tableData = row.data.list;
                this.form.total = row.data.total;
                this.loading = false;
            })
          
        },
       
        search: function () {
            this.loading = true;
            this.form.pageSize = 10;
            this.form.pageNumber = 1;
            this.init();
        },
        handleSizeChange: function (e) {
            this.form.pageSize = e;
            this.init();
        },
        handleCurrentChange: function (e) {
            this.form.pageNumber = e;
            this.init();
        },
        resetForm(formName) {
            this.form.staff_name = ''
            this.form.value = ''
            this.form.value1 = ''
            this.init();
        },
        openSaff: async function() {
            
            const res = await getStaffData();
            this.optionsVa = res.data;
            const des = await getRemindLossData();
            this.resForm.value1 = des.data.send_name;
            this.resForm.status = des.data.status;
            // this.resForm = {
            //     "status": 0,
            //     "value1": [],
            // };
            this.open = true;
        },
        editStaff: function(data){

            let editForm ={
                "id":data.id,
                "userid":data.userid,
                "name":data.name,
                "gender":data.gender,
                "alias":data.alias,
            }
            this.form = {...editForm};
            this.open=true;
        },
        subEditForm:function(data){
            this.$refs[data].validate((valid) => {
                if (valid) {
                    editUser(this.form).then((res)=>{
                        if(res.code==200){
                            this.msgSuccess(res.msg);
                            this.open=false;
                            this.init();
                        }else{
                            this.msgError(res.msg);
                        }
                    })
                }else{
                    return false;
                }
            })
        },
        delStaff:function(data) {
            this.$confirm('确定删除吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                delUser(data).then((res)=>{
                    if(res.code==200){
                        this.msgSuccess(res.msg);
                        this.init();
                    }else{
                        this.msgError(res.msg);
                    }
                })

            }).catch(() =>{
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async syncEmployee_a(){
            const res = await syncEmployee({
                page: 1
            })
            console.log('部门列表：', res.department)
            return res.department
        },
        async syncEmployee_b(item){
            const res = await syncEmployee({
                page: 2,
                department_id: item.id,
                department_name: item.name,
                department_pid: item.parentid,
                department_order: item.order,
            })
            console.log('同步部门-获取部门下员工列表：', res.data)
            return res.data
        },
        async syncEmployee_c(data){
            if (this.sync_number <= 0) {
                this.sync_type = 1;
            } else if (this.sync_number >= 100) {
                this.sync_type = 0;
            }
            if (this.sync_type > 0) {
                // 同步
                const res = await getClientDetail(data)
                console.log('同步：', res)
            } else {
                // 异步
                this.sync_number--
                getClientDetail(data).then(res => {
                    this.sync_number++
                    console.log('异步：', res)
                })
            }
            return false
        },
        syncConfirm(){
            this.$confirm('此操作稍有耗时, 是否继续?', '同步员工', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.syncEmployee()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消同步员工'
                });
            });
        },
        // async
        syncEmployee() {
            this.loading = true;
            // let b_list = await this.syncEmployee_a()
            // let list = []
            // for(let i = 0; i < b_list.length; i++) {
            //     let ret = await this.syncEmployee_b(b_list[i])
            //     if (ret.errcode === 0) {
            //         list = ret.userlist
            //         for(let l = 0; l < list.length; l++) {
            //             await this.syncEmployee_c({ userid: list[l].userid })
            //         }
            //     }
            //     this.$message.success('同步成功')
            // }
            // this.loading = false
            // this.init();

            syncEmployee({
                page: 1
            }).then(res_bb_list => {
                const resData = res_bb_list.data
                if (resData.errcode === 0) {
                    const bb_list = resData.department
                    console.log('t同步部门-获取部门列表', bb_list)
                    bb_list.forEach(item => {
                        syncEmployee({
                            page: 2,
                            department_id: item.id,
                            department_name: item.name,
                            department_pid: item.parentid,
                            department_order: item.order,
                        }).then(res_yg_list => {
                            const resData = res_yg_list.data
                            console.log('t同步部门-获取部门下员工列表', resData)
                            if (resData.errcode === 0) {
                                const dataList = resData.userlist
                                const total = dataList.length
                                let keep = 0
                                dataList.forEach(item => {
                                    const data = { userid: item.userid }
                                    syncEmployeeDesc(data).then(res => {
                                        console.log('t同步员工详情', res.data)
                                        if (res.code === 200) {
                                            this.msgSuccess('同步['+item.name+']成功！')
                                        } else {
                                            this.msgError(res.msg)
                                        }
                                        keep++
                                        if (keep >= total) {
                                            this.loading = false
                                            this.init();
                                        }
                                    })
                                })
                            }
                        })
                    })
                }


            })
        },
        syncEmployee_copy() {
            syncEmployee().then(res => {
                const resData = res.data
                console.log('t同步部门', resData)
                if (resData.errcode === 0) {
                    const dataList = resData.dept_user
                    for (let i = 0; i < dataList.length; i++) {
                        const item = dataList[i]
                        const data = { userid: item.userid }
                        syncEmployeeDesc(data).then((res) => {
                            console.log('t同步部门详情', res.data)
                        })
                    }
                    this.msgSuccess(resData.msg)
                } else {
                    this.msgError(resData.msg)
                }
            })
        },
      
    }
}

</script>

<style lang="scss" scoped>
.demo-form-inline {
    margin: 20px;

    .el-form-item {
        margin-bottom: 0;
    }
}
.el-form--inline .el-form-item {
    display: inline-block;
    vertical-align: top;
}

.orderListRuleForm .el-form-item {
    margin-bottom: 0;
}

.search-content {
    width: 100%;
    margin: 20px;
}


</style>